const formatNumber = (n) => {
	n = n.toString();
	return n[1] ? n : '0' + n;
};
// 倒计时
function countDown(that) {
	//倒计时函数
	let newTime = new Date().getTime();
	let endTime = that.data.endTime;
	let remainTime = endTime - newTime;
	let obj = null;
	let t = '';
	// 如果活动未结束，对时间进行处理
	if (remainTime > 0) {
		let time = remainTime / 1000;
		// 获取天、时、分、秒
		let day = parseInt(time / 86400);
		let hou = parseInt((time % 86400) / 3600);
		let min = parseInt(((time % 86400) % 3600) / 60);
		let sec = parseInt(((time % 86400) % 3600) % 60);
		obj = {
			day: formatNumber(day),
			hou: formatNumber(hou),
			min: formatNumber(min),
			sec: formatNumber(sec)
		};
	}
	t = setTimeout(function() {
		that.setData({
			countDownTxt: obj
		});
		countDown(that);
	}, 1000);
	if (remainTime <= 0) {
		clearTimeout(t);
	}
}
const hexStringToBuff = (str) => {
	//str='中国：WXHSH'
	const buffer = new ArrayBuffer(sumStrLength(str) * 4);
	const dataView = new DataView(buffer);
	var data = str.toString();
	var p = 0; //ArrayBuffer 偏移量
	for (var i = 0; i < data.length; i++) {
		if (isCN(data[i])) {
			//是中文
			//调用GBK 转码
			var t = gbk.encode(data[i]);
			for (var j = 0; j < 2; j++) {
				//var code = t[j * 2] + t[j * 2 + 1];
				var code = t[j * 3 + 1] + t[j * 3 + 2];
				var temp = parseInt(code, 16);
				//var temp = strToHexCharCode(code);
				dataView.setUint8(p++, temp);
			}
		} else {
			var temp = data.charCodeAt(i);
			dataView.setUint8(p++, temp);
		}
	}
	return buffer;
};

function sumStrLength(str) {
	var length = 0;
	var data = str.toString();
	for (var i = 0; i < data.length; i++) {
		if (isCN(data[i])) {
			//是中文
			length += 2;
		} else {
			length += 1;
		}
	}
	return length;
}

function isCN(str) {
	if (/^[\u3220-\uFA29]+$/.test(str)) {
		return true;
	} else {
		return false;
	}
}

//汉字转码
function hexStringToArrayBuffer(str) {
	const buffer = new ArrayBuffer(str.length / 2 + 1);
	const dataView = new DataView(buffer);
	for (var i = 0; i < str.length / 2; i++) {
		var temp = parseInt(str[i * 2] + str[i * 2 + 1], 16);
		dataView.setUint8(i, temp);
	}
	dataView.setUint8(str.length / 2, 10);
	return buffer;
}

//返回八位数组

//不带有汉字

function send0X0A() {
	const buffer = new ArrayBuffer(1);
	const dataView = new DataView(buffer);
	dataView.setUint8(0, 10);
	return buffer;
}

function throttle(fn, gapTime) {
	if (gapTime == null || gapTime == undefined) {
		gapTime = 2000;
	}
	let _lastTime = null;

	// 返回新的函数
	return function() {
		let _nowTime = +new Date();
		if (_nowTime - _lastTime > gapTime || !_lastTime) {
			fn.apply(this, arguments); //将this和参数传给原函数
			_lastTime = _nowTime;
		}
	};
}
// function toDate(number){
//   var n=number * 1000;
//   var date = new Date(n);
//   var Y = date.getFullYear() + '-';
//   var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
//   var D = date.getDate()<10 ? '0'+date.getDate() : date.getDate();
//   var H = date.getHours();
//   var F = date.getMinutes();
//   var S = date.getHours();
//   return (Y+M+D+' '+H+':'+F+':'+S)
// }

function toDate(number) {
	var n = number;
	var date = new Date(n);
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	if (date.getDate() < 10) {
		var D = '0' + date.getDate();
	} else {
		var D = date.getDate();
	}
	var H = date.getHours();
	var F = date.getMinutes();
	var S = date.getHours();
	if (H >= 1 && H <= 9) {
		H = '0' + H;
	}
	if (F >= 0 && F <= 9) {
		F = '0' + F;
	}
	if (S >= 0 && S <= 9) {
		S = '0' + S;
	}
	return Y + M + D + ' ' + H + ':' + F + ':' + S;
}

function apply(data, url, num) {
	uni.showLoading({
		title: '调起中...'
	});
	var timeStamp = (Date.parse(new Date()) / 1000).toString();
	var pkg = data.package;
	var nonceStr = data.nonceStr;
	uni.requestPayment({
		timeStamp: data.timeStamp,
		nonceStr: nonceStr,
		package: pkg,
		signType: 'MD5',
		paySign: data.paySign,
		success: function(res) {
			////////console.log(res)
			uni.hideLoading();
			uni.showModal({
				title: '',
				content: '支付成功！',
				showCancel: false,
				success: function(res) {
					if (res.confirm) {
						if (num == 1) {
							const pages = getCurrentPages(); // 获得最新路由
							const perpage = pages[pages.length - 1]; // 刷新最新路由 / 刷新当前页面
							//////console.log(pages)
							//////console.log(perpage)
							perpage.$vm.onLoad();
							perpage.$vm.onShow();
						} else if (num == 0) {
							uni.navigateBack();
						} else if (num == 2) {
							uni.reLaunch({
								url: '/pages/order/order'
							})
						} else {
							uni.navigateTo({
								url: url
							});
						}
					} else {}
				}
			});
		},
		fail() {
			uni.hideLoading();
			if (num == 2) {
				uni.reLaunch({
					url: '/pages/order/order'
				})
			} else {
				uni.navigateTo({
					url: url ? url : '/pages/order/order'
				});
			}
		}
	});
}
/* 加载动画相关 */
const showLoading = (tips = '加载中...') => {
	uni.showNavigationBarLoading();
	uni.showLoading({
		title: tips
	});
};
const hideLoading = () => {
	uni.hideLoading();
	uni.hideNavigationBarLoading();
};
const hideLoadingWithErrorTips = (err = '加载失败...') => {
	hideLoading();
	uni.showToast({
		title: err,
		icon: 'error',
		duration: 2000
	});
};

function currentday(str) {
	var date = new Date();
	var time = date.getHours() + ':' + date.getMinutes();
	// //////console.log(time)
	var seperator1 = '-';
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var strDate = date.getDate() + str;
	if (month >= 1 && month <= 9) {
		month = '0' + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = '0' + strDate;
	}
	var currentdate = year + seperator1 + month + seperator1 + strDate;
	return currentdate;
}

function currentdate() {
	var date = new Date();
	var time = date.getHours() + ':' + date.getMinutes();
	// //////console.log(time)
	var seperator1 = '-';
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = '0' + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = '0' + strDate;
	}
	var currentdate = year + seperator1 + month + seperator1 + strDate;
	return currentdate;
}

function currentdate1() {
	var date = new Date();
	var time = date.getHours() + ':' + date.getMinutes()+ ':' +(date.getSeconds()<10?('0'+date.getSeconds()):date.getSeconds());
	// //////console.log(time)
	var seperator1 = '-';
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = '0' + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = '0' + strDate;
	}
	var currentdate = year + seperator1 + month + seperator1 + strDate + ' ' + time;
	return currentdate;
}

function currentdate4() {
	var date = new Date();
	var time = date.getHours() + ':' + date.getMinutes()
	// + ':' +(date.getSeconds()<10?('0'+date.getSeconds()):date.getSeconds());
	// //////console.log(time)
	var seperator1 = '-';
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = '0' + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = '0' + strDate;
	}
	var currentdate = time;
	return currentdate;
}
function currentdate2() {
	var date = new Date();
	var time = date.getHours() + ':' + date.getMinutes();
	// //////console.log(time)

	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = '0' + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = '0' + strDate;
	}
	var currentdate = time;
	return currentdate;
}

function chooseimage(url, tempFilePaths, callback) {
	//////console.log(22)
	var that = this;
	var token =  uni.getStorageSync('token')?uni.getStorageSync('token'):uni.getStorageSync('JSTOKEN');
	////console.log(token)
	uni.chooseImage({
		count: 1,
		// 默认9
		// 可以指定是原图还是压缩图，默认二者都有
		sizeType: ['original', 'compressed'],
		// 可以指定来源是相册还是相机，默认二者都有
		sourceType: ['album', 'camera'],
		// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
		success: function(res) {
			//console.log(res)
			// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
			var tempFilePaths3 = res.tempFilePaths;
			//////console.log(22)
			// callback(tempFilePaths3)
			// return tempFilePaths3;
			uni.uploadFile({
				url: url,
				filePath: tempFilePaths3[0],
				formData: {
					token: uni.getStorageSync('token')?uni.getStorageSync('token'):uni.getStorageSync('JSTOKEN')
				},
				name: 'file',
				success: function(res) {
					//////console.log(22)
					//打印
					var data = JSON.parse(res.data);
					//console.log(data)
					callback(data);
					return data;
				},
				fail: function(err) {}
			});
		}
	});
}

function chooseimage1(url, tempFilePaths, callback) {
	var that = this;
	uni.chooseVideo({
	  sourceType: ['album', 'camera'], // 可选择的视频来源
	  success: function (res) {
	    // 返回选定视频的本地文件路径
	    ////console.log(res);
	    ////console.log('视频的本地路径：' + res.tempFilePath);
		uni.uploadFile({
			url: url,
			filePath: res.tempFilePath,
			formData: {
				token: uni.getStorageSync('token')?uni.getStorageSync('token'):uni.getStorageSync('JSTOKEN')
			},
			name: 'file',
			success: function(res) {
				//////console.log(22)
				//打印
				var data = JSON.parse(res.data);
				//////console.log(data)
				callback(data);
				return data;
			},
			fail: function(err) {}
		});
	  },
	  fail: function (err) {
	    console.error('选择视频失败：' + err);
	  }
	});
}

function chooseimage2(url, tempFilePaths, callback) {
	//////console.log(22)
	var that = this;
	uni.chooseFile({
	  extension:['.mp3'], // 可选择的视频来源
	  success: function (res) {
	    // 返回选定视频的本地文件路径
	    //console.log(res);
	    //console.log('视频的本地路径：' + res.tempFilePaths);
		uni.uploadFile({
			url: url,
			filePath: res.tempFilePaths[0],
			formData: {
				token: uni.getStorageSync('token')?uni.getStorageSync('token'):uni.getStorageSync('JSTOKEN'),
			},
			fileType:'audio',
			name: 'file',
			// header: {
			// 	'content-type': 'multipart/form-data',
			// 	'content-type': 'application/x-www-form-urlencoded'
			// },
			success: function(res) {
				//////console.log(22)
				//打印
				var data = JSON.parse(res.data);
				//////console.log(data)
				callback(data);
				return data;
			},
			fail: function(err) {}
		});
	  },
	  fail: function (err) {
	    console.error('选择视频失败：' + err);
	  }
	});
}
const random = function(str) {
	let num = str
		.split('')
		.map((char) => char.charCodeAt())
		.join('');
	return Math.sin(num).toString().split('.')[1].slice(0, 16);
};
// 拨打电话
function telephone(res) {
	//console.log(res)
	uni.makePhoneCall({
		phoneNumber: res
	});
}
// 一键复制事件
function copyBtn(e) {
	uni.setClipboardData({
		data: e,
		success: function(res) {
			uni.showToast({
				title: '复制成功'
			});
		}
	});
}
// 七天日期
function dealTime(num,dates) {
	// num：未来天数
	if(dates){
		var time = new Date(dates);
	}else{
		var time = new Date();
	}
	 // 获取当前时间日期
	// var date1= new Date(Date.parse(dates.replace(/-/g,  "/")))
	var date = new Date(time.setDate(time.getDate() + num)).getDate(); //这里先获取日期，在按需求设置日期，最后获取需要的
	var year = time.getFullYear(); //获取年份
	var month = time.getMonth() + 1; // 获取月份
	var day = time.getDay(); //  获取星期
	switch (day) {
		//  格式化
		case 0:
			day = '日';
			break;
		case 1:
			day = '一';
			break;
		case 2:
			day = '二';
			break;
		case 3:
			day = '三';
			break;
		case 4:
			day = '四';
			break;
		case 5:
			day = '五';
			break;
		case 6:
			day = '六';
			break;
	}
	var obj = {
		days: date,
		day: month + '.' + date,
		day1: month + '月' + date + '日',
		checks: false,
		month: month,
		week: day,
		year:year,
		date: year + '-' + month + '-' + date,
		date1: year + '年' + month + '月' + date+ '日'
	};
	return obj; // 返回对象
}

function btndownload(url) {
	uni.showLoading({
		title: '调起中...'
	});
	// 文件下载
	uni.downloadFile({
		url: url,//下载资源的 url
		success: res => {
			////console.log(res);
			if (res.statusCode === 200) {
				////console.log('下载成功');
				//文件保存到本地
				
				uni.saveFile({
					tempFilePath: res.tempFilePath, //临时路径
					success: function(res) {
						////console.log(res);
						// uni.showToast({
						// 	icon: 'none',
						// 	mask: true,
						// 	title: '文件已保存', //保存路径
						// 	duration: 3000
						// });
						setTimeout(() => {
							//打开文档查看
							uni.openDocument({
								filePath: res.savedFilePath,showMenu: true, // 允许出现分享功能
								success: function(res) {
									////console.log('打开文档成功');
								},
								fail: function() {
									////console.log('打开失败');
								}
							});
						uni.hideLoading();
						}, 3000);
					},
					fail: function() {
						////console.log('保存失败');
						uni.hideLoading();
					}
				});
			}
			////console.log(res.tempFilePath);

		},
		fail: function() {
			////console.log('下载失败');
			uni.showToast({
				icon: 'none',
				mask: true,
				title: '失败请重新下载'
			});
		}
	});

}
// 前8天日期
function getLast8Days() {
  const today = new Date();
  const last8Days = [];
 
  for (let i = 0; i < 8; i++) {
	const day = new Date(today);
	day.setDate(day.getDate() - i);
	last8Days.push(day.toISOString().split('T')[0]);
  }
 
  return last8Days;
}
// 计算两个日期相差多少天
function getDiffDay(date_1, date_2){
       let totalDays, diffDate
       let myDate_1 = Date.parse(date_1)
       let myDate_2 = Date.parse(date_2)
       diffDate = Math.abs(myDate_1 - myDate_2) 
       totalDays = Math.floor(diffDate / (1000 * 3600 * 24))
       return totalDays 
 }
function getDiffDays(year,month){
	// var time = new Date();
	// var date = new Date(time.setDate(time.getDate() + num)).getDate(); //这里先获取日期，在按需求设置日期，最后获取需要的
	// var year = time.getFullYear(); //获取年份
	// var month = time.getMonth() + 1; // 获取月份
	// var day = time.getDay(); //  获取星期
	////console.log(year)
	var month = (month<10?('0'+month):month)
	////console.log(month)
	let dates = new Date(2024, 06, 0)
	////console.log(dates)
	return dates 
}

function currentdate3(){
  var date1 = new Date();
  var date2 = new Date(date1);
  //-30为30天前，+30可以获得30天后的日期
  date2.setDate(date1.getDate() + 30);
  //30天前（月份判断是否小于10，小于10的前面+0）
  var agoDay = `${date2.getFullYear()}-${date2.getMonth() + 1<10?`0${date2.getMonth() + 1}`:date2.getMonth() + 1}-${date2.getDate()}`;
  return agoDay
}
/**
 * 时间格式化parseTime
 * 
 */
function parseTime(time, cFormat) {
	////console.log(time)
	////console.log(cFormat)
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}
// 预览图片
function preview(img,arr){
	uni.previewImage({
		current: img, // 当前显示图片索引
		urls: arr // 需要预览的图片http链接列表
	});
}
// 是否微信内部
function isWechat() {
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == "micromessenger") {
			return true;
		} else {
			return false;
		}
}
module.exports = {
	isWechat:isWechat,
	preview:preview,
	parseTime:parseTime,
	currentdate4:currentdate4,
	getDiffDays:getDiffDays,
	getDiffDay:getDiffDay,
	getLast8Days:getLast8Days,
	btndownload: btndownload,
	copyBtn: copyBtn,
	dealTime: dealTime,
	telephone: telephone,
	toDate: toDate,
	// 时间戳转换
	countDown: countDown,
	apply: apply,
	currentday: currentday,
	chooseimage: chooseimage,
	chooseimage1:chooseimage1,
	chooseimage2: chooseimage2,
	throttle: throttle,
	hexStringToArrayBuffer: hexStringToArrayBuffer,
	hexStringToBuff: hexStringToBuff,
	send0X0A: send0X0A,
	showLoading: showLoading,
	hideLoading: hideLoading,
	hideLoadingWithErrorTips: hideLoadingWithErrorTips,
	currentdate: currentdate,
	currentdate1: currentdate1,
	currentdate2: currentdate2,
	currentdate3:currentdate3,
	random: random
};